package com.xuetang.controller.admin;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.xuetang.common.ApiResponse;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${file.upload.path:/tmp/uploads}")
    private String uploadPath;

    @Value("${file.access.url:http://localhost:8080/files}")
    private String accessUrl;

    /**
     * 上传图片
     * 
     * @param file 图片文件
     * @return 上传结果
     */
    @PostMapping("/image")
    public ApiResponse uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ApiResponse.error("上传文件不能为空");
        }

        try {
            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 获取文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + suffix;

            // 保存文件
            Path targetPath = Paths.get(uploadPath, newFileName);
            Files.copy(file.getInputStream(), targetPath);

            // 构建访问URL
            String fileUrl = accessUrl + "/" + newFileName;

            // 返回结果
            Map<String, String> data = new HashMap<>();
            data.put("url", fileUrl);
            data.put("filename", newFileName);

            return ApiResponse.success(data);
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResponse.error("文件上传失败: " + e.getMessage());
        }
    }
}